package com.game.utils;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

public class CodeImageTool {
	public static final int pre_length=3;
	public static final int beh_length=3;
	public static final  byte[] code=new byte[]{'a','1','b','2','c','3'};
	
	public Bitmap getCodedBitMap(Resources res,String filename){
		Bitmap img=null;
		try {
			InputStream codedStream=res.getAssets().open(filename.trim());
			BufferedInputStream bis=new BufferedInputStream(codedStream);
//			DataInputStream dis=new DataInputStream(bis);
		    ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
		    byte[] buffer = new byte[1024];
	        int len=0;
	        while ((len = bis.read(buffer)) > 0) { 
	        	bos.write(buffer,0,len);
	        }            
	        byte[] dat = bos.toByteArray();
	        codedStream.close();
	        bis.close();
//	        dis.close();
	        bos.close();
		    //读取有效数据
			img=BitmapFactory.decodeByteArray(dat,pre_length, dat.length-(pre_length+beh_length));
		} catch (Exception e){}
		return img;
	}
	
	public static void main(String[] args) {
		System.out.println("start");
	    new CodeImageTool().setBitmap("E:/pngs", "E:/change/");
	}
	
	public void setBitmap(String path,String savepath){
		try{
			File saveFolder = new File(savepath);
			if(!saveFolder.exists())
				saveFolder.mkdir();
		    File file=new File(path);
		    File[] list = file.listFiles();
		    int size=list.length;
		    for (int i = 0; i < size; i++) {
			    if (list[i].isFile()) {
				    File fx = new File(""+list[i].getAbsolutePath());
				    FileInputStream fis= new FileInputStream(fx);
				    BufferedInputStream bis =new BufferedInputStream(fis);
//					DataInputStream dis=new DataInputStream(bis);
			        ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
			        byte[] buffer = new byte[1024];
			        int len=0;
			        //前面加上
			        bos.write(code,0,pre_length);
			        while ((len = bis.read(buffer)) > 0) { 
			        	bos.write(buffer,0,len);
			        } 
			        //后面加上
			        bos.write(code,0,beh_length);
			        byte[] dat = bos.toByteArray();
			        fis.close();
			        bis.close();
//			        dis.close();
			        bos.close();
				    FileOutputStream fos=new FileOutputStream(savepath.trim()+list[i].getName());
				    DataOutputStream dos=new DataOutputStream(fos);
				    dos.write(dat, 0, dat.length);
				    fos.close();
				    dos.close();
			    }
	       }
		} catch (Exception e) {}
		
	}
}